#!/usr/bin/env python
# coding:utf-8
from PoboAPI import *
import datetime
import numpy as np

#开始时间，用于初始化一些参数，分钟级别回测
#用真格量化 python实现，在真格量化 https://quant.pobo.net.cn 上运行，如果有问题 可加群 726895887 咨询
def OnStart(context) :
    print("I\'m starting...")
    #登录交易账号，需在主页用户管理中设置账号，并把期货测试替换成您的账户名称
    context.myacc = None
    if "回测期货" in context.accounts :
        print("登录交易账号[回测期货]")
        if context.accounts["回测期货"].Login() :
            context.myacc = context.accounts["回测期货"]

def OnMarketQuotationInitialEx(context, exchange,daynight):
    if exchange != 'SHFE':
        return
    #获取主力合约
    g.code = GetMainContract('SHFE', 'rb',20)
    #订阅K线数据，用于驱动OnBar事件
    SubscribeBar(g.code, BarType.Min) 
    
#实时行情事件，当有新行情出现时调用该事件Ex
def OnBar(context,code,bartype):
    #过滤掉不需要的行情通知
    if code != g.code:
        return
    dyndata = GetQuote(g.code)
    
    
    option = PBObj()
    option.buysellflag = '0' #查询持仓
    pos = context.myacc.GetPositions(option)
    
    
    option = PBObj()
#     option.StartDate = datetime.datetime(2019, 3,18, 11, 25)
#     option.EndDate = datetime.datetime(2019, 3,18, 11, 27)
    option.Count=10
    
    
    klinedata = GetHisData(g.code, BarType.Min, option)
    
    if klinedata and klinedata[-2].open>0 and klinedata[-3].open>0:
        
    
        growth1=(klinedata[-3].close-klinedata[-2].open)/klinedata[-3].open#前一分钟涨幅
        
        growth2=(klinedata[-2].close-klinedata[-2].open)/klinedata[-2].open#本分钟涨幅
        
        if growth1>0:
            
            print(growth1)
            print(growth2)
        
            growthdiff=(growth2-growth1)/growth1#涨幅变动
    
    #计算均线
# #     MA = GetIndicator("MA",code,params=(5,10),bar_type = BarType.Day)
# #     MA1 = MA["MA(5)"]
# #     MA2 = MA["MA(10)"]
#     if len(MA2)<2:
#         return
#     #ma1上穿ma2时买入螺纹主力1手
#     elif MA1[-1] >= MA2[-1] and MA1[-2]<MA2[-2]:
            if growthdiff>0.3 and growth1>0 and growth2>0 and len(pos)==0:

                QuickInsertOrder(context.myacc,g.code,'buy','open',dyndata.now,10)
        #ma1下穿ma2时卖出平仓
    #     elif MA1[-1] <= MA2[-1] and MA1[-2]>MA2[-2]:
            if len(pos)>0 and growthdiff<0.1:
                QuickInsertOrder(context.myacc,g.code,'sell','close',dyndata.now,10)
        
